{% extends "base.html" %}

{% block content %}
<style>
    :root {
        --primary-color: #F0B90B;
        --grab-color: #f39c12;
        --alert-color: #e74c3c;
        --completed-color: #2ecc71;
        --background-light: #ffffff;
        --background-card: #f8f9fa;
        --text-dark: #212529;
        --text-muted: #6c757d;
        --border-color: #dee2e6;
    }

    .airdrop-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    .section-title {
        margin: 30px 0 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid var(--primary-color);
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .section-title i {
        color: var(--primary-color);
    }

    .airdrops-table-wrapper {
        overflow-x: auto;
        margin-bottom: 30px;
        border-radius: 8px;
        background-color: var(--background-light);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.03);
        border: 1px solid var(--border-color);
    }

    .airdrops-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 0;
    }

    .airdrops-table th {
        background-color: rgba(240, 185, 11, 0.1);
        padding: 12px 15px;
        text-align: left;
        font-weight: 600;
        color: var(--text-dark);
        border-bottom: 2px solid var(--border-color);
    }

    .airdrops-table td {
        padding: 12px 15px;
        border-bottom: 1px solid var(--border-color);
    }

    .airdrops-table tbody tr:hover {
        background-color: rgba(240, 185, 11, 0.05);
    }

    .loading {
        text-align: center;
        padding: 30px !important;
    }

    .loading .spinner {
        border: 4px solid rgba(240, 185, 11, 0.2);
        border-radius: 50%;
        border-top: 4px solid var(--primary-color);
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 0 auto 15px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .token-name {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .token-symbol {
        font-weight: bold;
        font-size: 1.1rem;
    }

    .token-fullname {
        font-size: 0.9rem;
        color: var(--text-muted);
    }

    .points-badge {
        background-color: rgba(240, 185, 11, 0.15);
        color: #856404;
        padding: 3px 8px;
        border-radius: 4px;
        font-weight: 500;
    }

    .price-container {
        margin-top: 5px;
    }

    .value-text {
        font-size: 0.9rem;
        margin-top: 3px;
    }

    .exchange-price-value {
        color: var(--text-dark);
    }

    .dex-price-value {
        color: var(--primary-color);
    }

    .completed-icon {
        color: var(--completed-color);
        margin-left: 8px;
    }

    .tge-info-icon {
        color: var(--primary-color);
        cursor: pointer;
        margin-right: 5px;
    }

    .reminder-bell {
        background: none;
        border: none;
        color: var(--text-dark);
        cursor: pointer;
        font-size: 1.2rem;
        padding: 0;
        margin-left: 8px;
    }

    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1050;
    }

    .modal-content {
        background-color: var(--background-light);
        border-radius: 10px;
        width: 90%;
        max-width: 500px;
        overflow: hidden;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
    }

    .modal-header {
        padding: 15px 20px;
        background-color: rgba(240, 185, 11, 0.1);
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .modal-header h3 {
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
        color: var(--text-dark);
    }

    .modal-close {
        background: none;
        border: none;
        color: var(--text-dark);
        font-size: 1.5rem;
        cursor: pointer;
        opacity: 0.7;
        transition: opacity 0.2s;
    }

    .modal-close:hover {
        opacity: 1;
    }

    .modal-body {
        padding: 20px;
    }

    .reminder-text {
        margin-bottom: 20px;
        color: var(--text-dark);
    }

    .twitter-btn {
        display: block;
        background-color: #1da1f2;
        color: white;
        text-align: center;
        padding: 10px;
        border-radius: 5px;
        text-decoration: none;
        font-weight: bold;
        transition: background-color 0.3s;
        margin-top: 15px;
    }

    .twitter-btn:hover {
        background-color: #1a91da;
        color: white;
    }

    .tge-info-row {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px solid var(--border-color);
    }

    .tge-label {
        font-weight: 600;
        color: var(--text-dark);
    }

    .tge-value {
        color: var(--text-dark);
    }

    .rotating {
        animation: rotate 1s linear;
    }

    @keyframes rotate {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    /* 状态标签样式 */
    .status-tag {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 0.8rem;
        margin-left: 6px;
        font-weight: 500;
    }

    .status-announced {
        background-color: #d1ecf1;
        color: #0c5460;
    }

    .status-completed {
        background-color: #d4edda;
        color: #155724;
    }

    .status-ongoing {
        background-color: #fff3cd;
        color: #856404;
    }

    /* 空投类型样式 */
    .type-tag {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 0.8rem;
        margin-left: 6px;
        font-weight: 500;
    }

    .type-alpha {
        background-color: #e2d9f3;
        color: #4a2a7f;
    }

    .type-tge {
        background-color: #f8d7da;
        color: #721c24;
    }

    .type-grab {
        background-color: #d1e7dd;
        color: #0a3622;
    }

    .type-claim {
        background-color: #fff3cd;
        color: #664d03;
    }

    /* 阶段标签 */
    .phase-tag {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 0.8rem;
        margin-left: 6px;
        background-color: #e2e3e5;
        color: #41464b;
        font-weight: 500;
    }

    .refresh-btn {
        background-color: var(--primary-color);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 5px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s;
    }

    .refresh-btn:hover {
        background-color: #d8a500;
        transform: translateY(-2px);
    }

    .empty-state {
        text-align: center;
        padding: 40px 20px;
    }

    .empty-state i {
        font-size: 3rem;
        color: #ced4da;
        margin-bottom: 15px;
    }

    .empty-state p {
        color: var(--text-muted);
        margin-bottom: 0;
    }

    .time-cell {
        font-weight: 500;
    }

    .card-header {
        background-color: rgba(240, 185, 11, 0.1);
        border-bottom: 1px solid var(--border-color);
        font-weight: 600;
    }

    .token-logo {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: linear-gradient(135deg, #f0b90b 0%, #f8d053 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 16px;
        margin-right: 10px;
    }

    .today-highlight {
        background-color: rgba(240, 185, 11, 0.1);
    }

    .value-badge {
        background-color: rgba(40, 167, 69, 0.15);
        color: #1e7e34;
        padding: 3px 8px;
        border-radius: 4px;
        font-weight: 500;
        margin-top: 5px;
        display: inline-block;
    }

    .price-loading {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid rgba(240, 185, 11, 0.2);
        border-top: 2px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 5px;
    }

    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1100;
    }

    .toast {
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
</style>

<div class="toast-container">
    <div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <i class="bi bi-info-circle-fill text-primary me-2"></i>
            <strong class="me-auto">系统通知</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body"></div>
    </div>
</div>

<div class="airdrop-container">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2 class="section-title">
            <i class="bi bi-gift-fill"></i> 今日空投
        </h2>
        <div class="text-muted" id="current-date">2025年8月16日</div>
    </div>

    <div class="card mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span>今日空投活动</span>
            <span class="badge bg-warning" id="today-count">加载中...</span>
        </div>
        <div class="airdrops-table-wrapper">
            <table class="airdrops-table" id="today-airdrops">
                <thead>
                    <tr>
                        <th>项目</th>
                        <th>积分</th>
                        <th>数量</th>
                        <th>时间</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="5" class="loading">
                            <div class="spinner"></div>
                            <p>加载今日空投数据...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-3 mt-5">
        <h2 class="section-title"><i class="bi bi-calendar-event"></i> 空投预告</h2>
        <div class="text-muted" id="upcoming-range">未来7天</div>
    </div>

    <div class="card mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span>即将到来的空投</span>
            <span class="badge bg-info" id="upcoming-count">加载中...</span>
        </div>
        <div class="airdrops-table-wrapper">
            <table class="airdrops-table" id="upcoming-airdrops">
                <thead>
                    <tr>
                        <th>项目</th>
                        <th>积分</th>
                        <th>数量</th>
                        <th>时间</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="5" class="loading">
                            <div class="spinner"></div>
                            <p>加载空投预告数据...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-white">
            <i class="bi bi-info-circle me-2"></i>空投日历使用说明
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <h5><i class="bi bi-tag-fill text-primary me-2"></i>状态标签说明</h5>
                    <ul class="list-group">
                        <li class="list-group-item border-0">
                            <span class="status-tag status-announced">announced</span> - 空投详情已发布，即将开始
                        </li>
                        <li class="list-group-item border-0">
                            <span class="status-tag status-ongoing">ongoing</span> - 空投活动正在进行
                        </li>
                        <li class="list-group-item border-0">
                            <span class="status-tag status-completed">completed</span> - 空投已结束，代币已发放
                        </li>
                    </ul>
                </div>
                <div class="col-md-6">
                    <h5><i class="bi bi-grid-1x2-fill text-warning me-2"></i>空投类型说明</h5>
                    <ul class="list-group">
                        <li class="list-group-item border-0">
                            <span class="type-tag type-alpha">alpha</span> - 早期测试版空投，通常收益最高
                        </li>
                        <li class="list-group-item border-0">
                            <span class="type-tag type-tge">tge</span> - 代币生成事件空投
                        </li>
                        <li class="list-group-item border-0">
                            <span class="type-tag type-grab">grab</span> - 先到先得型空投
                        </li>
                        <li class="list-group-item border-0">
                            <span class="type-tag type-claim">claim</span> - 申领型空投
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- TGE信息弹窗 -->
<div id="tgeInfoModal" class="modal-overlay" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="bi bi-bar-chart-fill" style="color: #F0B90B;"></i> <span id="tgeModalTitle">TGE统计</span></h3>
            <button class="modal-close" onclick="closeTgeInfoModal()">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
        <div class="modal-body">
            <div class="tge-info-content">
                <div class="tge-info-row">
                    <span class="tge-label">投入：</span>
                    <span class="tge-value">
                        <input type="number" id="bnbInput" value="3.0" min="0" step="0.1"
                               style="width: 100px; padding: 5px; border: 1px solid #ddd; border-radius: 5px;"
                               onchange="updateCostCalculation()" onblur="formatBnbInput(this)"> BNB
                    </span>
                </div>

                <div class="tge-info-row">
                    <span class="tge-label">已募：</span>
                    <span class="tge-value"><span id="tgeActualBnb">1500</span> BNB</span>
                </div>

                <div class="tge-info-row">
                    <span class="tge-label">超募：</span>
                    <span class="tge-value"><span id="tgeOversubscription">5.2</span>x</span>
                </div>

                <div class="tge-info-row">
                    <span class="tge-label">成本：</span>
                    <span class="tge-value"><span id="tgeCost">0.5769</span> BNB</span>
                </div>

                <div class="tge-info-row">
                    <span class="tge-label">可得：</span>
                    <span class="tge-value"><span id="tgeTokenAmount">2000</span> <span id="tgeTokenSymbol">DOT</span></span>
                </div>

                <div class="mt-4">
                    <button class="btn btn-warning w-100 py-2">
                        <i class="bi bi-bell me-2"></i>设置空投提醒
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 存储价格数据的全局变量
    let tokenPrices = {};

    document.addEventListener('DOMContentLoaded', function() {
        // 初始化页面
        initializeApp();

        // 设置当前日期
        const now = new Date();
        document.getElementById('current-date').textContent = formatDate(now);

        // 设置预告日期范围
        const nextWeek = new Date();
        nextWeek.setDate(now.getDate() + 7);
        document.getElementById('upcoming-range').textContent = `至 ${formatDate(nextWeek)}`;

        // 加载数据
        loadAirdropData();
    });

    function initializeApp() {
        // 初始化toast
        const toastEl = document.getElementById('toast');
        const toast = new bootstrap.Toast(toastEl, {
            autohide: true,
            delay: 3000
        });

        // 绑定刷新按钮
        const refreshButton = document.getElementById('refreshButton');
        if (refreshButton) {
            refreshButton.addEventListener('click', function() {
                const icon = this.querySelector('i');
                icon.classList.add('rotating');

                // 显示加载状态
                showLoading();

                setTimeout(() => {
                    icon.classList.remove('rotating');
                    loadAirdropData(true);
                }, 800);
            });
        }
    }

    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}年${month}月${day}日`;
    }

    function showLoading() {
        const todayBody = document.querySelector('#today-airdrops tbody');
        const upcomingBody = document.querySelector('#upcoming-airdrops tbody');

        todayBody.innerHTML = `
            <tr>
                <td colspan="5" class="loading">
                    <div class="spinner"></div>
                    <p>加载中...</p>
                </td>
            </tr>
        `;

        upcomingBody.innerHTML = `
            <tr>
                <td colspan="5" class="loading">
                    <div class="spinner"></div>
                    <p>加载中...</p>
                </td>
            </tr>
        `;
    }

    function showToast(message, type = 'info') {
        const toastEl = document.getElementById('toast');
        const toastBody = toastEl.querySelector('.toast-body');
        const toastHeaderIcon = toastEl.querySelector('.toast-header i');

        toastBody.textContent = message;

        // 设置图标和颜色
        if (type === 'success') {
            toastHeaderIcon.className = 'bi bi-check-circle-fill text-success me-2';
        } else if (type === 'error') {
            toastHeaderIcon.className = 'bi bi-exclamation-triangle-fill text-danger me-2';
        } else {
            toastHeaderIcon.className = 'bi bi-info-circle-fill text-primary me-2';
        }

        const toast = bootstrap.Toast.getOrCreateInstance(toastEl);
        toast.show();
    }

    function formatBnbInput(input) {
        let value = parseFloat(input.value);
        if (isNaN(value) || value < 0) {
            value = 0;
        }
        input.value = value.toFixed(1);
        updateCostCalculation();
    }

    function loadAirdropData(forceRefresh = false) {
        const apiUrl = `/api/airdrop_data?fresh=${forceRefresh ? '1' : '0'}`;

        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应异常');
                }
                return response.json();
            })
            .then(data => {
                // 处理API返回的数据
                const processedData = processApiData(data);

                // 获取所有代币符号
                const tokens = getAllTokens(processedData);

                // 获取价格数据
                fetchTokenPrices(tokens)
                    .then(prices => {
                        tokenPrices = prices;

                        // 渲染数据
                        renderAirdrops(processedData);

                        // 更新计数
                        document.getElementById('today-count').textContent = `${processedData.today.length} 个项目`;
                        document.getElementById('upcoming-count').textContent = `${processedData.upcoming.length} 个项目`;

                        // 显示成功消息
                        showToast('数据加载成功！', 'success');
                    })
                    .catch(error => {
                        console.error('获取价格数据失败:', error);
                        showToast(`价格数据加载失败: ${error.message}`, 'error');

                        // 使用空价格数据渲染
                        tokenPrices = {};
                        renderAirdrops(processedData);

                        // 更新计数
                        document.getElementById('today-count').textContent = `${processedData.today.length} 个项目`;
                        document.getElementById('upcoming-count').textContent = `${processedData.upcoming.length} 个项目`;
                    });
            })
            .catch(error => {
                console.error('获取空投数据失败:', error);
                showToast(`加载失败: ${error.message}`, 'error');

                // 显示错误状态
                const todayBody = document.querySelector('#today-airdrops tbody');
                const upcomingBody = document.querySelector('#upcoming-airdrops tbody');

                todayBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="text-center py-4 text-danger">
                            <i class="bi bi-exclamation-triangle me-2"></i>${error.message || '加载失败，请稍后重试'}
                        </td>
                    </tr>
                `;

                upcomingBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="text-center py-4 text-danger">
                            <i class="bi bi-exclamation-triangle me-2"></i>${error.message || '加载失败，请稍后重试'}
                        </td>
                    </tr>
                `;
            });
    }

    // 从数据中提取所有代币符号
    function getAllTokens(data) {
        const tokens = new Set();

        // 添加今日空投的代币
        data.today.forEach(airdrop => {
            if (airdrop.token) {
                tokens.add(airdrop.token);
            }
        });

        // 添加预告空投的代币
        data.upcoming.forEach(airdrop => {
            if (airdrop.token) {
                tokens.add(airdrop.token);
            }
        });

        return Array.from(tokens);
    }

    // 获取代币价格
    function fetchTokenPrices(tokens) {
        if (tokens.length === 0) {
            return Promise.resolve({});
        }

        const apiUrl = `/api/token_price?tokens=${tokens.join(',')}`;

        return fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error('价格API响应异常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.prices) {
                    return data.prices;
                } else {
                    throw new Error(data.message || '获取价格失败');
                }
            });
    }

    function processApiData(apiData) {
        if (!apiData || !apiData.airdrops || !Array.isArray(apiData.airdrops)) {
            return { today: [], upcoming: [] };
        }

        const now = new Date();
        const today = new Date(now);
        today.setHours(0, 0, 0, 0);

        // 获取今天的日期字符串（YYYY-MM-DD）
        const todayStr = formatDateForComparison(today);

        // 获取明天的日期
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);
        const tomorrowStr = formatDateForComparison(tomorrow);

        // 处理每个空投的时间信息
        const processedAirdrops = apiData.airdrops.map(airdrop => {
            const processed = {...airdrop};

            // 初始化日期时间属性
            processed.adjustedDate = processed.date;
            processed.adjustedTime = processed.time;
            processed.isPhase2 = processed.phase === 2;

            // 如果是二阶段空投，计算调整后的时间
            if (processed.isPhase2 && processed.time) {
                const [hours, minutes] = processed.time.split(':');
                let adjustedHours = parseInt(hours, 10) + 18;

                // 处理日期变化（如果小时超过24）
                let dateObj = new Date(processed.date);
                if (adjustedHours >= 24) {
                    adjustedHours -= 24;
                    dateObj.setDate(dateObj.getDate() + 1);
                }

                // 更新调整后的日期和时间
                processed.adjustedDate = formatDateForComparison(dateObj);
                processed.adjustedTime = `${String(adjustedHours).padStart(2, '0')}:${minutes}`;
            }

            // 标记是否为今日空投
            processed.isToday = processed.adjustedDate === todayStr;

            return processed;
        });

        // 分离今日和未来的空投
        const todayAirdrops = processedAirdrops.filter(airdrop => airdrop.isToday);

        const upcomingAirdrops = processedAirdrops.filter(airdrop => {
            // 跳过今日空投
            if (airdrop.isToday) return false;

            // 比较调整后的日期
            return airdrop.adjustedDate >= tomorrowStr;
        });

        // 按时间排序
        todayAirdrops.sort((a, b) => {
            // 优先按时间排序
            if (a.adjustedTime && b.adjustedTime) {
                return a.adjustedTime.localeCompare(b.adjustedTime);
            }

            // 其次按系统时间戳排序
            return (a.system_timestamp || 0) - (b.system_timestamp || 0);
        });

        upcomingAirdrops.sort((a, b) => {
            // 优先按日期排序
            if (a.adjustedDate !== b.adjustedDate) {
                return a.adjustedDate.localeCompare(b.adjustedDate);
            }

            // 其次按时间排序
            if (a.adjustedTime && b.adjustedTime) {
                return a.adjustedTime.localeCompare(b.adjustedTime);
            }

            // 最后按系统时间戳排序
            return (a.system_timestamp || 0) - (b.system_timestamp || 0);
        });

        return {
            today: todayAirdrops,
            upcoming: upcomingAirdrops
        };
    }

    function formatDateForComparison(date) {
        if (typeof date === 'string') {
            return date;
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    function renderAirdrops(data) {
        renderAirdropTable(data.today, 'today-airdrops');
        renderAirdropTable(data.upcoming, 'upcoming-airdrops');
    }

    function renderAirdropTable(airdrops, tableId) {
        const tableBody = document.querySelector(`#${tableId} tbody`);

        if (!airdrops || airdrops.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="5" class="empty-state">
                        <i class="bi bi-calendar-x"></i>
                        <p>暂无数据</p>
                    </td>
                </tr>
            `;
            return;
        }

        tableBody.innerHTML = '';

        airdrops.forEach(airdrop => {
            const row = document.createElement('tr');

            // 如果是今日空投，添加高亮样式
            if (tableId === 'today-airdrops') {
                row.classList.add('today-highlight');
            }

            // 项目列
            const tokenCell = document.createElement('td');
            tokenCell.innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="token-logo">${airdrop.token ? airdrop.token.substring(0, 2) : 'NA'}</div>
                    <div>
                        <div class="token-symbol">${airdrop.token || 'N/A'}</div>
                        <div class="token-fullname">${airdrop.name || '未知项目'}</div>
                    </div>
                </div>
            `;

            // 积分列
            const pointsCell = document.createElement('td');
            pointsCell.innerHTML = `<span class="points-badge">${airdrop.points || '-'}</span>`;

            // 数量列
            const amountCell = document.createElement('td');

            // 计算实际价值 - 仅对今日空投显示价值
            let valueHtml = '';
            const token = airdrop.token || '';
            const amount = airdrop.amount || '';

            if (tableId === 'today-airdrops') {
                if (token && tokenPrices[token] && amount) {
                    try {
                        // 解析数量（去除逗号等）
                        const amountValue = parseFloat(amount.replace(/,/g, ''));
                        if (!isNaN(amountValue)) {
                            // 使用DEX价格计算价值
                            const value = amountValue * tokenPrices[token].dex_price;
                            valueHtml = `
                                <div class="value-text dex-price-value">
                                    <i class="bi bi-link-45deg" title="去中心化交易所价格(链上)"></i>$${value.toFixed(2)}
                                </div>
                            `;
                        }
                    } catch (e) {
                        console.error(`计算价值失败: ${e.message}`);
                    }
                }

                // 如果没有价值信息，显示加载中
                if (!valueHtml && token) {
                    valueHtml = `
                        <div class="value-text dex-price-value">
                            <i class="bi bi-link-45deg" title="去中心化交易所价格(链上)"></i>
                            <span class="price-loading"></span>
                        </div>
                    `;
                }
            }

            amountCell.innerHTML = `
                <span class="points-badge">${amount} ${token || ''}</span>
                ${valueHtml ? `<div class="price-container" data-token="${token}">${valueHtml}</div>` : ''}
            `;

            // 时间列
            const timeCell = document.createElement('td');
            let timeText = '待公布';

            if (airdrop.adjustedTime) {
                timeText = airdrop.adjustedTime;
            } else if (airdrop.time) {
                timeText = airdrop.time;
            }

            // 添加二阶段标记
            if (airdrop.isPhase2) {
                timeText += ' (二阶段)';
            }

            // 添加日期（如果不是今天）
            if (tableId === 'upcoming-airdrops' && airdrop.adjustedDate) {
                timeText = `${airdrop.adjustedDate} ${timeText}`;
            }

            timeCell.innerHTML = `<div class="time-cell">${timeText}</div>`;

            // 状态列
            const statusCell = document.createElement('td');

            // 状态标签
            let statusTag = '';
            if (airdrop.status) {
                statusTag = `<span class="status-tag status-${airdrop.status}">${airdrop.status}</span>`;
            }

            // 类型标签
            let typeTag = '';
            if (airdrop.type) {
                typeTag = `<span class="type-tag type-${airdrop.type}">${airdrop.type}</span>`;
            }

            // 阶段标签
            let phaseTag = '';
            if (airdrop.phase) {
                phaseTag = `<span class="phase-tag">阶段 ${airdrop.phase}</span>`;
            }

            // 完成状态
            let completedIcon = '';
            if (airdrop.completed) {
                completedIcon = `<i class="bi bi-check-circle-fill completed-icon" title="已完成"></i>`;
            }

            statusCell.innerHTML = `
                <div>
                    ${statusTag}
                    ${typeTag}
                    ${phaseTag}
                    ${completedIcon}
                </div>
            `;

            // 添加TGE点击事件
            if (airdrop.type === 'tge') {
                const tgeElement = statusCell.querySelector('.type-tge');
                tgeElement.style.cursor = 'pointer';
                tgeElement.addEventListener('click', () => {
                    showTgeInfo(airdrop.token, 1000, 1500, 5.2);
                });
            }

            row.appendChild(tokenCell);
            row.appendChild(pointsCell);
            row.appendChild(amountCell);
            row.appendChild(timeCell);
            row.appendChild(statusCell);
            tableBody.appendChild(row);
        });
    }

    function showTgeInfo(token, targetBnb, actualBnb, oversubscription) {
        document.getElementById('tgeActualBnb').textContent = actualBnb;
        document.getElementById('tgeOversubscription').textContent = oversubscription;
        document.getElementById('tgeModalTitle').textContent = `${token} TGE统计`;
        document.getElementById('tgeTokenSymbol').textContent = token;
        updateCostCalculation();
        document.getElementById('tgeInfoModal').style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }

    function closeTgeInfoModal() {
        document.getElementById('tgeInfoModal').style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    function updateCostCalculation() {
        const bnbInput = parseFloat(document.getElementById('bnbInput').value) || 0;
        const actualBnb = parseFloat(document.getElementById('tgeActualBnb').textContent) || 1;
        const oversubscription = parseFloat(document.getElementById('tgeOversubscription').textContent) || 1;

        const cost = bnbInput / oversubscription;
        const tokenAmount = (bnbInput / actualBnb) * 1000;

        document.getElementById('tgeCost').textContent = cost.toFixed(4);
        document.getElementById('tgeTokenAmount').textContent = tokenAmount.toFixed(2);
    }
</script>
{% endblock %}